package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 补货工单完成处理
 */
@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyMsgHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Autowired
    private ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //解析消息
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);

        //修改设备表的最新补货时间
        vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                .eq(VendingMachineEntity::getInnerCode,supplyContract.getInnerCode())
                .set(VendingMachineEntity::getLastSupplyTime , LocalDateTime.now()));

        //查询货道表的信息
        List<ChannelEntity> channelEntityList = channelService.list(Wrappers.<ChannelEntity>lambdaQuery()
                .eq(ChannelEntity::getInnerCode, supplyContract.getInnerCode()));
        //遍历补货信息
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();
        for (SupplyChannel channel : supplyData) {
            //遍历查询到的货道信息
            for (ChannelEntity channelEntity : channelEntityList) {
                //如果货道编号相同,则是同一货道,同一商品
                if (channelEntity.getChannelCode() == channel.getChannelId()) {
                    //判断补货数量 + 货道剩余商品数 是否大于货道最大容量
                    int capacity = channelEntity.getCurrentCapacity() + channel.getCapacity();
                    if (capacity > channelEntity.getMaxCapacity()) {
                        throw new LogicException("商品数量错误");
                    }
                    //修改货道商品数
                    channelEntity.setCurrentCapacity(capacity);
                    //修改最新补货时间
                    channelEntity.setLastSupplyTime(LocalDateTime.now());
                    //修改货道数据
                    channelService.updateById(channelEntity);
                }
            }

        }
    }
}
